package cn.lijida.weiwei.favor.commons.exception;

import java.sql.SQLIntegrityConstraintViolationException;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import cn.lijida.weiwei.favor.commons.utils.ReturnT;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {
	
	/**
     * 唯一索引
     *
     * @return 错误返回消息
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ReturnT<String> sqlIntegrityConstraintViolationExceptionErrorHandler(SQLIntegrityConstraintViolationException e) {
        log.info("唯一索引异常：{}", e.getMessage());
        
        ReturnT<String> r = new ReturnT<>(ReturnT.FAIL_CODE, "记录已存在");
        return r;
    }

    /**
     * hibernate validator 数据绑定验证异常拦截
     *
     * @param e 绑定验证异常
     * @return 错误返回消息
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public ReturnT<String> validateErrorHandler(BindException e) {
        ObjectError error = e.getAllErrors().get(0);
        log.info("数据验证异常：{}", error.getDefaultMessage());
        
        ReturnT<String> r = new ReturnT<>(ReturnT.FAIL_CODE, error.getDefaultMessage());
        return r;
    }

    /**
     * hibernate validator 数据绑定验证异常拦截
     *
     * @param e 绑定验证异常
     * @return 错误返回消息
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnT<String> validateErrorHandler(MethodArgumentNotValidException e) {
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        log.info("数据验证异常：{}", error.getDefaultMessage());
        ReturnT<String> r = new ReturnT<>(ReturnT.FAIL_CODE, error.getDefaultMessage());
        return r;
    }
    
    /**
     * 全局错误
     *
     * @return 错误返回消息
     */
    /*
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    public ReturnT<String> exceptionErrorHandler(Exception e) {
        log.info("全局异常：{}", e.getMessage());
        
        ReturnT<String> r = new ReturnT<>(ReturnT.FAIL_CODE, e.getMessage());
        return r;
    }*/
}